@model CaipuGuanliXitong.Models.DailyPurchaseDto
@{
    ViewData["Title"] = "计算每日采购食材";
}

<div class="container">
    <h2>计算每日采购食材</h2>
    
    @if (TempData["SuccessMessage"] != null)
    {
        <div class="alert alert-success">
            @TempData["SuccessMessage"]
        </div>
    }
    
    @if (TempData["ErrorMessage"] != null)
    {
        <div class="alert alert-danger">
            @TempData["ErrorMessage"]
        </div>
    }
    
    <form asp-action="Calculate" method="post">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="date">日期</label>
                    <input type="date" class="form-control" id="date" name="date" value="@(ViewBag.Date.ToString("yyyy-MM-dd") ?? DateTime.Now.ToString("yyyy-MM-dd"))" required>
                </div>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-md-12">
                <h4>用餐人数</h4>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>餐次</th>
                            <th>男性人数</th>
                            <th>女性人数</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>早餐</td>
                            <td><input type="number" class="form-control" name="breakfastMale" min="0" value="600" required></td>
                            <td><input type="number" class="form-control" name="breakfastFemale" min="0" value="600" required></td>
                        </tr>
                        <tr>
                            <td>午餐</td>
                            <td><input type="number" class="form-control" name="lunchMale" min="0" value="600" required></td>
                            <td><input type="number" class="form-control" name="lunchFemale" min="0" value="600" required></td>
                        </tr>
                        <tr>
                            <td>晚餐</td>
                            <td><input type="number" class="form-control" name="dinnerMale" min="0" value="600" required></td>
                            <td><input type="number" class="form-control" name="dinnerFemale" min="0" value="600" required></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-md-12">
                <button type="submit" class="btn btn-primary">计算采购清单</button>
                <a class="btn btn-secondary" asp-action="Index">返回</a>
            </div>
        </div>
    </form>
    
    @if (Model.BreakfastDetails != null && Model.BreakfastDetails.Any() || 
         Model.LunchDetails != null && Model.LunchDetails.Any() || 
         Model.DinnerDetails != null && Model.DinnerDetails.Any())
    {
        <form asp-action="Save" method="post" id="saveForm">
            @Html.AntiForgeryToken()
            <input type="hidden" asp-for="Date" />
            <input type="hidden" asp-for="BreakfastMaleCount" />
            <input type="hidden" asp-for="BreakfastFemaleCount" />
            <input type="hidden" asp-for="LunchMaleCount" />
            <input type="hidden" asp-for="LunchFemaleCount" />
            <input type="hidden" asp-for="DinnerMaleCount" />
            <input type="hidden" asp-for="DinnerFemaleCount" />
            <input type="hidden" asp-for="BreakfastTotalAmount" />
            <input type="hidden" asp-for="LunchTotalAmount" />
            <input type="hidden" asp-for="DinnerTotalAmount" />
            <input type="hidden" asp-for="TotalAmount" />
            
            <div class="row mt-5">
                <div class="col-md-12">
                    <h2>计算结果</h2>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h4>基本信息</h4>
                                </div>
                                <div class="card-body">
                                    <dl class="row">
                                        <dt class="col-sm-2">日期</dt>
                                        <dd class="col-sm-10">@Model.Date.ToString("yyyy年MM月dd日")</dd>
                                        
                                        <dt class="col-sm-2">用餐人数</dt>
                                        <dd class="col-sm-10">
                                            早餐: 男 @Model.BreakfastMaleCount 人, 女 @Model.BreakfastFemaleCount 人<br>
                                            午餐: 男 @Model.LunchMaleCount 人, 女 @Model.LunchFemaleCount 人<br>
                                            晚餐: 男 @Model.DinnerMaleCount 人, 女 @Model.DinnerFemaleCount 人
                                        </dd>
                                    </dl>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    @if (Model.MenuRecipes != null && Model.MenuRecipes.Any())
                    {
                        <div class="row">
                            <div class="col-md-12">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h4>当日菜谱</h4>
                                    </div>
                                    <div class="card-body">
                                        <!-- 早餐菜谱 -->
                                        <div class="meal-section mb-4">
                                            <h5>早餐菜谱</h5>
                                            <div class="table-responsive">
                                                <table class="table table-striped table-bordered meal-table" id="breakfastMenuTable">
                                                    <thead>
                                                        <tr>
                                                            <th>性别</th>
                                                            <th>菜谱</th>
                                                            <th>份数</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        @for (int i = 0; i < Model.MenuRecipes.Count; i++)
                                                        {
                                                            if (Model.MenuRecipes[i].MealType == "早餐")
                                                            {
                                                                <tr>
                                                                    <td>
                                                                        <select class="form-control" name="MenuRecipes[@i].Gender">
                                                                            <option value="男性" selected="@(Model.MenuRecipes[i].Gender == "男性")">男性</option>
                                                                            <option value="女性" selected="@(Model.MenuRecipes[i].Gender == "女性")">女性</option>
                                                                        </select>
                                                                        <input type="hidden" name="MenuRecipes[@i].MealType" value="早餐" />
                                                                        <input type="hidden" name="MenuRecipes[@i].Id" value="@Model.MenuRecipes[i].Id" />
                                                                    </td>
                                                                    <td>
                                                                        <div class="autocomplete-wrapper">
                                                                            <input type="text" class="form-control recipe-autocomplete" name="MenuRecipes[@i].RecipeNames" value="@Model.MenuRecipes[i].RecipeNames" data-row-index="@i">
                                                                            <div class="autocomplete-suggestions" id="recipeSuggestions-@i"></div>
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <input type="number" class="form-control" name="MenuRecipes[@i].Count" value="@Model.MenuRecipes[i].Count" min="0">
                                                                        <input type="hidden" name="MenuRecipes.Index" value="@i" />
                                                                    </td>
                                                                    <td>
                                                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                                    </td>
                                                                </tr>
                                                            }
                                                        }
                                                    </tbody>
                                                </table>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-success" onclick="addMealRecipe('breakfast')">添加早餐菜谱</button>
                                        </div>
                        
                                        <!-- 午餐菜谱 -->
                                        <div class="meal-section mb-4">
                                            <h5>午餐菜谱</h5>
                                            <div class="table-responsive">
                                                <table class="table table-striped table-bordered meal-table" id="lunchMenuTable">
                                                    <thead>
                                                        <tr>
                                                            <th>性别</th>
                                                            <th>菜谱</th>
                                                            <th>份数</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        @for (int i = 0; i < Model.MenuRecipes.Count; i++)
                                                        {
                                                            if (Model.MenuRecipes[i].MealType == "午餐")
                                                            {
                                                                <tr>
                                                                    <td>
                                                                        <select class="form-control" name="MenuRecipes[@i].Gender">
                                                                            <option value="男性" selected="@(Model.MenuRecipes[i].Gender == "男性")">男性</option>
                                                                            <option value="女性" selected="@(Model.MenuRecipes[i].Gender == "女性")">女性</option>
                                                                        </select>
                                                                        <input type="hidden" name="MenuRecipes[@i].MealType" value="午餐" />
                                                                        <input type="hidden" name="MenuRecipes[@i].Id" value="@Model.MenuRecipes[i].Id" />
                                                                    </td>
                                                                    <td>
                                                                        <div class="autocomplete-wrapper">
                                                                            <input type="text" class="form-control recipe-autocomplete" name="MenuRecipes[@i].RecipeNames" value="@Model.MenuRecipes[i].RecipeNames" data-row-index="@i">
                                                                            <div class="autocomplete-suggestions" id="recipeSuggestions-@i"></div>
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <input type="number" class="form-control" name="MenuRecipes[@i].Count" value="@Model.MenuRecipes[i].Count" min="0">
                                                                        <input type="hidden" name="MenuRecipes.Index" value="@i" />
                                                                    </td>
                                                                    <td>
                                                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                                    </td>
                                                                </tr>
                                                            }
                                                        }
                                                    </tbody>
                                                </table>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-success" onclick="addMealRecipe('lunch')">添加午餐菜谱</button>
                                        </div>
                        
                                        <!-- 晚餐菜谱 -->
                                        <div class="meal-section mb-4">
                                            <h5>晚餐菜谱</h5>
                                            <div class="table-responsive">
                                                <table class="table table-striped table-bordered meal-table" id="dinnerMenuTable">
                                                    <thead>
                                                        <tr>
                                                            <th>性别</th>
                                                            <th>菜谱</th>
                                                            <th>份数</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        @for (int i = 0; i < Model.MenuRecipes.Count; i++)
                                                        {
                                                            if (Model.MenuRecipes[i].MealType == "晚餐")
                                                            {
                                                                <tr>
                                                                    <td>
                                                                        <select class="form-control" name="MenuRecipes[@i].Gender">
                                                                            <option value="男性" selected="@(Model.MenuRecipes[i].Gender == "男性")">男性</option>
                                                                            <option value="女性" selected="@(Model.MenuRecipes[i].Gender == "女性")">女性</option>
                                                                        </select>
                                                                        <input type="hidden" name="MenuRecipes[@i].MealType" value="晚餐" />
                                                                        <input type="hidden" name="MenuRecipes[@i].Id" value="@Model.MenuRecipes[i].Id" />
                                                                    </td>
                                                                    <td>
                                                                        <div class="autocomplete-wrapper">
                                                                            <input type="text" class="form-control recipe-autocomplete" name="MenuRecipes[@i].RecipeNames" value="@Model.MenuRecipes[i].RecipeNames" data-row-index="@i">
                                                                            <div class="autocomplete-suggestions" id="recipeSuggestions-@i"></div>
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <input type="number" class="form-control" name="MenuRecipes[@i].Count" value="@Model.MenuRecipes[i].Count" min="0">
                                                                        <input type="hidden" name="MenuRecipes.Index" value="@i" />
                                                                    </td>
                                                                    <td>
                                                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                                    </td>
                                                                </tr>
                                                            }
                                                        }
                                                    </tbody>
                                                </table>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-success" onclick="addMealRecipe('dinner')">添加晚餐菜谱</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    }
                    
                    <!-- 早餐采购清单 -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h4>早餐采购清单</h4>
                                    <button type="button" class="btn btn-sm btn-success float-right" onclick="addBreakfastDetail()">添加食材</button>
                                </div>
                                <div class="card-body">
                                    @if (Model.BreakfastDetails.Any())
                                    {
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered" id="breakfastDetailsTable">
                                                <thead>
                                                    <tr>
                                                        <th>食材名称</th>
                                                        <th>单位</th>
                                                        <th>数量</th>
                                                        <th>单价</th>
                                                        <th>金额</th>
                                                        <th>操作</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @for (int i = 0; i < Model.BreakfastDetails.Count; i++)
                                                    {
                                                        <tr>
                                                            <td>
                                                                <div class="autocomplete-wrapper">
                                                                    <input type="text" class="form-control ingredient-autocomplete" name="BreakfastDetails[@i].IngredientName" value="@Model.BreakfastDetails[i].IngredientName" data-row-index="@i" data-meal-type="breakfast">
                                                                    <input type="hidden" name="BreakfastDetails[@i].IngredientId" value="@Model.BreakfastDetails[i].IngredientId" class="ingredient-id">
                                                                    <input type="hidden" name="BreakfastDetails.Index" value="@i" />
                                                                    <div class="autocomplete-suggestions" id="ingredientSuggestions-@i-breakfast"></div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control" name="BreakfastDetails[@i].IngredientUnit" value="@Model.BreakfastDetails[i].IngredientUnit">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control quantity" name="BreakfastDetails[@i].Quantity" value="@Model.BreakfastDetails[i].Quantity.ToString("F3")" min="0" step="0.001">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control price" name="BreakfastDetails[@i].Price" value="@Model.BreakfastDetails[i].Price.ToString("F2")" min="0" step="0.01">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control total" name="BreakfastDetails[@i].TotalAmount" value="@Model.BreakfastDetails[i].TotalAmount.ToString("F2")" min="0" step="0.01" readonly>
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                            </td>
                                                        </tr>
                                                    }
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="4" class="text-right">小计</th>
                                                        <th><span id="breakfastTotal">@Model.BreakfastTotalAmount.ToString("F2")</span></th>
                                                        <th></th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    }
                                    else
                                    {
                                        <p>早餐无需采购食材</p>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 午餐采购清单 -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h4>午餐采购清单</h4>
                                    <button type="button" class="btn btn-sm btn-success float-right" onclick="addLunchDetail()">添加食材</button>
                                </div>
                                <div class="card-body">
                                    @if (Model.LunchDetails.Any())
                                    {
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered" id="lunchDetailsTable">
                                                <thead>
                                                    <tr>
                                                        <th>食材名称</th>
                                                        <th>单位</th>
                                                        <th>数量</th>
                                                        <th>单价</th>
                                                        <th>金额</th>
                                                        <th>操作</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @for (int i = 0; i < Model.LunchDetails.Count; i++)
                                                    {
                                                        <tr>
                                                            <td>
                                                                <div class="autocomplete-wrapper">
                                                                    <input type="text" class="form-control ingredient-autocomplete" name="LunchDetails[@i].IngredientName" value="@Model.LunchDetails[i].IngredientName" data-row-index="@i" data-meal-type="lunch">
                                                                    <input type="hidden" name="LunchDetails[@i].IngredientId" value="@Model.LunchDetails[i].IngredientId" class="ingredient-id">
                                                                    <input type="hidden" name="LunchDetails.Index" value="@i" />
                                                                    <div class="autocomplete-suggestions" id="ingredientSuggestions-@i-lunch"></div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control" name="LunchDetails[@i].IngredientUnit" value="@Model.LunchDetails[i].IngredientUnit">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control quantity" name="LunchDetails[@i].Quantity" value="@Model.LunchDetails[i].Quantity.ToString("F3")" min="0" step="0.001">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control price" name="LunchDetails[@i].Price" value="@Model.LunchDetails[i].Price.ToString("F2")" min="0" step="0.01">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control total" name="LunchDetails[@i].TotalAmount" value="@Model.LunchDetails[i].TotalAmount.ToString("F2")" min="0" step="0.01" readonly>
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                            </td>
                                                        </tr>
                                                    }
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="4" class="text-right">小计</th>
                                                        <th><span id="lunchTotal">@Model.LunchTotalAmount.ToString("F2")</span></th>
                                                        <th></th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    }
                                    else
                                    {
                                        <p>午餐无需采购食材</p>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 晚餐采购清单 -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h4>晚餐采购清单</h4>
                                    <button type="button" class="btn btn-sm btn-success float-right" onclick="addDinnerDetail()">添加食材</button>
                                </div>
                                <div class="card-body">
                                    @if (Model.DinnerDetails.Any())
                                    {
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered" id="dinnerDetailsTable">
                                                <thead>
                                                    <tr>
                                                        <th>食材名称</th>
                                                        <th>单位</th>
                                                        <th>数量</th>
                                                        <th>单价</th>
                                                        <th>金额</th>
                                                        <th>操作</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @for (int i = 0; i < Model.DinnerDetails.Count; i++)
                                                    {
                                                        <tr>
                                                            <td>
                                                                <div class="autocomplete-wrapper">
                                                                    <input type="text" class="form-control ingredient-autocomplete" name="DinnerDetails[@i].IngredientName" value="@Model.DinnerDetails[i].IngredientName" data-row-index="@i" data-meal-type="dinner">
                                                                    <input type="hidden" name="DinnerDetails[@i].IngredientId" value="@Model.DinnerDetails[i].IngredientId" class="ingredient-id">
                                                                    <input type="hidden" name="DinnerDetails.Index" value="@i" />
                                                                    <div class="autocomplete-suggestions" id="ingredientSuggestions-@i-dinner"></div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control" name="DinnerDetails[@i].IngredientUnit" value="@Model.DinnerDetails[i].IngredientUnit">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control quantity" name="DinnerDetails[@i].Quantity" value="@Model.DinnerDetails[i].Quantity.ToString("F3")" min="0" step="0.001">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control price" name="DinnerDetails[@i].Price" value="@Model.DinnerDetails[i].Price.ToString("F2")" min="0" step="0.01">
                                                            </td>
                                                            <td>
                                                                <input type="number" class="form-control total" name="DinnerDetails[@i].TotalAmount" value="@Model.DinnerDetails[i].TotalAmount.ToString("F2")" min="0" step="0.01" readonly>
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                                                            </td>
                                                        </tr>
                                                    }
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="4" class="text-right">小计</th>
                                                        <th><span id="dinnerTotal">@Model.DinnerTotalAmount.ToString("F2")</span></th>
                                                        <th></th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    }
                                    else
                                    {
                                        <p>晚餐无需采购食材</p>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4>采购总计</h4>
                                </div>
                                <div class="card-body">
                                    <dl class="row">
                                        <dt class="col-sm-3">早餐采购金额</dt>
                                        <dd class="col-sm-9">@Model.BreakfastTotalAmount.ToString("F2") 元</dd>
                                        
                                        <dt class="col-sm-3">午餐采购金额</dt>
                                        <dd class="col-sm-9">@Model.LunchTotalAmount.ToString("F2") 元</dd>
                                        
                                        <dt class="col-sm-3">晚餐采购金额</dt>
                                        <dd class="col-sm-9">@Model.DinnerTotalAmount.ToString("F2") 元</dd>
                                        
                                        <dt class="col-sm-3">总采购金额</dt>
                                        <dd class="col-sm-9"><strong>@Model.TotalAmount.ToString("F2") 元</strong></dd>
                                    </dl>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-success" form="saveForm">保存采购清单</button>
                            <a class="btn btn-secondary" asp-action="Index">返回</a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    }
</div>

@section Scripts {
    <script>
        // 存储食材和菜谱数据
        let ingredients = [];
        let cookBooks = [];
        
        // 初始化自动完成数据
        function initializeAutocompleteData() {
            // 获取所有食材数据
            fetch('/Ingredient/GetAllIngredients')
                .then(response => response.json())
                .then(data => {
                    ingredients = data;
                })
                .catch(error => console.error('Error loading ingredients:', error));
                
            // 获取所有菜谱数据
            fetch('/CookBook/GetAllCookBooks')
                .then(response => response.json())
                .then(data => {
                    cookBooks = data;
                })
                .catch(error => console.error('Error loading cookbooks:', error));
        }
        
        // 初始化自动完成功能
        function initializeAutocomplete() {
            // 为现有的食材输入框添加自动完成功能
            document.querySelectorAll('.ingredient-autocomplete').forEach(input => {
                input.addEventListener('input', function() {
                    const value = this.value.toLowerCase();
                    const rowIndex = this.getAttribute('data-row-index');
                    const mealType = this.getAttribute('data-meal-type');
                    const suggestionsContainer = document.getElementById('ingredientSuggestions-' + rowIndex + '-' + mealType);
                    
                    if (value.length < 1) {
                        suggestionsContainer.innerHTML = '';
                        suggestionsContainer.classList.remove('show');
                        return;
                    }
                    
                    // 过滤食材
                    const filteredIngredients = ingredients.filter(ingredient => 
                        ingredient.name.toLowerCase().includes(value)
                    );
                    
                    // 显示建议
                    displayIngredientSuggestions(filteredIngredients, suggestionsContainer, this);
                });
                
                // 点击其他地方隐藏建议
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.autocomplete-wrapper')) {
                        document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                            container.innerHTML = '';
                            container.classList.remove('show');
                        });
                    }
                });
            });
            
            // 为现有的菜谱输入框添加自动完成功能
            document.querySelectorAll('.recipe-autocomplete').forEach(input => {
                input.addEventListener('input', function() {
                    const value = this.value.toLowerCase();
                    const rowIndex = this.getAttribute('data-row-index');
                    const suggestionsContainer = document.getElementById('recipeSuggestions-' + rowIndex);
                    
                    if (value.length < 1) {
                        suggestionsContainer.innerHTML = '';
                        suggestionsContainer.classList.remove('show');
                        return;
                    }
                    
                    // 过滤菜谱
                    const filteredCookBooks = cookBooks.filter(cookBook => 
                        cookBook.name.toLowerCase().includes(value)
                    );
                    
                    // 显示建议
                    displayRecipeSuggestions(filteredCookBooks, suggestionsContainer, this);
                });
                
                // 点击其他地方隐藏建议
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.autocomplete-wrapper')) {
                        document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                            container.innerHTML = '';
                            container.classList.remove('show');
                        });
                    }
                });
            });
        }
        
        // 显示食材建议
        function displayIngredientSuggestions(suggestions, container, inputElement) {
            if (suggestions.length === 0) {
                container.innerHTML = '';
                container.classList.remove('show');
                return;
            }
            
            let suggestionsHTML = '<ul class="suggestions-list">';
            suggestions.slice(0, 10).forEach(ingredient => {
                suggestionsHTML += '<li data-id="' + ingredient.id + '" data-name="' + ingredient.name + '" data-unit="' + ingredient.unit + '" data-price="' + ingredient.price + '">' + ingredient.name + '</li>';
            });
            suggestionsHTML += '</ul>';
            
            container.innerHTML = suggestionsHTML;
            container.classList.add('show');
            
            // 为每个建议项添加点击事件
            container.querySelectorAll('li').forEach(item => {
                item.addEventListener('click', function() {
                    inputElement.value = this.getAttribute('data-name');
                    container.innerHTML = '';
                    container.classList.remove('show');
                    
                    // 填充单位和价格
                    const row = inputElement.closest('tr');
                    const unitInput = row.querySelector('[name$=".IngredientUnit"]');
                    const priceInput = row.querySelector('[name$=".Price"]');
                    const ingredientIdInput = row.querySelector('.ingredient-id');
                    
                    if (unitInput) unitInput.value = this.getAttribute('data-unit');
                    if (priceInput) priceInput.value = parseFloat(this.getAttribute('data-price')).toFixed(2);
                    if (ingredientIdInput) ingredientIdInput.value = this.getAttribute('data-id');
                    
                    // 触发金额计算
                    const quantityInput = row.querySelector('.quantity');
                    if (quantityInput && priceInput) {
                        const quantity = parseFloat(quantityInput.value) || 0;
                        const price = parseFloat(priceInput.value) || 0;
                        const total = quantity * price;
                        
                        const totalInput = row.querySelector('.total');
                        if (totalInput) totalInput.value = total.toFixed(2);
                        updateTotals();
                    }
                });
            });
        }
        
        // 显示菜谱建议
        function displayRecipeSuggestions(suggestions, container, inputElement) {
            if (suggestions.length === 0) {
                container.innerHTML = '';
                container.classList.remove('show');
                return;
            }
            
            let suggestionsHTML = '<ul class="suggestions-list">';
            suggestions.slice(0, 10).forEach(cookBook => {
                suggestionsHTML += '<li data-id="' + cookBook.id + '" data-name="' + cookBook.name + '">' + cookBook.name + '</li>';
            });
            suggestionsHTML += '</ul>';
            
            container.innerHTML = suggestionsHTML;
            container.classList.add('show');
            
            // 为每个建议项添加点击事件
            container.querySelectorAll('li').forEach(item => {
                item.addEventListener('click', function() {
                    inputElement.value = this.getAttribute('data-name');
                    container.innerHTML = '';
                    container.classList.remove('show');
                });
            });
        }
        
        // 添加特定餐次的菜谱行
        function addMealRecipe(mealType) {
            // 根据餐次确定表格和行索引
            var tableId = '';
            var rowCount = 0;
            
            switch(mealType) {
                case 'breakfast':
                    tableId = 'breakfastMenuTable';
                    rowCount = document.getElementById('breakfastMenuTable').querySelector('tbody tr').length;
                    break;
                case 'lunch':
                    tableId = 'lunchMenuTable';
                    rowCount = document.getElementById('lunchMenuTable').querySelector('tbody tr').length;
                    break;
                case 'dinner':
                    tableId = 'dinnerMenuTable';
                    rowCount = document.getElementById('dinnerMenuTable').querySelector('tbody tr').length;
                    break;
            }
            
            var table = document.getElementById(tableId).getElementsByTagName('tbody')[0];
            var row = table.insertRow(rowCount);
            
            row.innerHTML = `
                <td>
                    <select class="form-control" name="MenuRecipes[${rowCount}].Gender">
                        <option value="男性">男性</option>
                        <option value="女性">女性</option>
                    </select>
                    <input type="hidden" name="MenuRecipes[${rowCount}].MealType" value="\${mealType === 'breakfast' ? '早餐' : mealType === 'lunch' ? '午餐' : '晚餐'}" />
                    <input type="hidden" name="MenuRecipes[${rowCount}].Id" value="0" />
                </td>
                <td>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="form-control recipe-autocomplete" name="MenuRecipes[${rowCount}].RecipeNames" data-row-index="\${rowCount}">
                        <div class="autocomplete-suggestions" id="recipeSuggestions-\${rowCount}"></div>
                    </div>
                </td>
                <td>
                    <input type="number" class="form-control" name="MenuRecipes[${rowCount}].Count" min="0" value="0">
                    <input type="hidden" name="MenuRecipes.Index" value="\${rowCount}" />
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                </td>
            `;
            
            // 为新添加的输入框初始化自动完成功能
            const newInput = row.querySelector('.recipe-autocomplete');
            newInput.addEventListener('input', function() {
                const value = this.value.toLowerCase();
                const rowIndex = this.getAttribute('data-row-index');
                const suggestionsContainer = document.getElementById('recipeSuggestions-' + rowIndex);
                
                if (value.length < 1) {
                    suggestionsContainer.innerHTML = '';
                    suggestionsContainer.classList.remove('show');
                    return;
                }
                
                // 过滤菜谱
                const filteredCookBooks = cookBooks.filter(cookBook => 
                    cookBook.name.toLowerCase().includes(value)
                );
                
                // 显示建议
                displayRecipeSuggestions(filteredCookBooks, suggestionsContainer, this);
            });
            
            // 点击其他地方隐藏建议
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                        container.innerHTML = '';
                        container.classList.remove('show');
                    });
                }
            });
        }
        
        // 添加早餐食材行
        function addBreakfastDetail() {
            var table = document.getElementById("breakfastDetailsTable").getElementsByTagName('tbody')[0];
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            
            row.innerHTML = `
                <td>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="form-control ingredient-autocomplete" name="BreakfastDetails[${rowCount}].IngredientName" data-row-index="${rowCount}" data-meal-type="breakfast">
                        <input type="hidden" name="BreakfastDetails[${rowCount}].IngredientId" value="0" class="ingredient-id">
                        <input type="hidden" name="BreakfastDetails.Index" value="${rowCount}" />
                        <div class="autocomplete-suggestions" id="ingredientSuggestions-${rowCount}-breakfast"></div>
                    </div>
                </td>
                <td>
                    <input type="text" class="form-control" name="BreakfastDetails[${rowCount}].IngredientUnit">
                </td>
                <td>
                    <input type="number" class="form-control quantity" name="BreakfastDetails[${rowCount}].Quantity" min="0" step="0.001" value="0">
                </td>
                <td>
                    <input type="number" class="form-control price" name="BreakfastDetails[${rowCount}].Price" min="0" step="0.01" value="0">
                </td>
                <td>
                    <input type="number" class="form-control total" name="BreakfastDetails[${rowCount}].TotalAmount" min="0" step="0.01" value="0" readonly>
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                </td>
            `;
            
            // 为新添加的输入框初始化自动完成功能
            const newInput = row.querySelector('.ingredient-autocomplete');
            newInput.addEventListener('input', function() {
                const value = this.value.toLowerCase();
                const rowIndex = this.getAttribute('data-row-index');
                const mealType = this.getAttribute('data-meal-type');
                const suggestionsContainer = document.getElementById('ingredientSuggestions-' + rowIndex + '-' + mealType);
                
                if (value.length < 1) {
                    suggestionsContainer.innerHTML = '';
                    suggestionsContainer.classList.remove('show');
                    return;
                }
                
                // 过滤食材
                const filteredIngredients = ingredients.filter(ingredient => 
                    ingredient.name.toLowerCase().includes(value)
                );
                
                // 显示建议
                displayIngredientSuggestions(filteredIngredients, suggestionsContainer, this);
            });
            
            // 点击其他地方隐藏建议
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                        container.innerHTML = '';
                        container.classList.remove('show');
                    });
                }
            });
            
            // 添加事件监听器
            addCalculationListeners(row);
        }
        
        // 添加午餐食材行
        function addLunchDetail() {
            var table = document.getElementById("lunchDetailsTable").getElementsByTagName('tbody')[0];
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            
            row.innerHTML = `
                <td>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="form-control ingredient-autocomplete" name="LunchDetails[${rowCount}].IngredientName" data-row-index="${rowCount}" data-meal-type="lunch">
                        <input type="hidden" name="LunchDetails[${rowCount}].IngredientId" value="0" class="ingredient-id">
                        <input type="hidden" name="LunchDetails.Index" value="${rowCount}" />
                        <div class="autocomplete-suggestions" id="ingredientSuggestions-${rowCount}-lunch"></div>
                    </div>
                </td>
                <td>
                    <input type="text" class="form-control" name="LunchDetails[${rowCount}].IngredientUnit">
                </td>
                <td>
                    <input type="number" class="form-control quantity" name="LunchDetails[${rowCount}].Quantity" min="0" step="0.001" value="0">
                </td>
                <td>
                    <input type="number" class="form-control price" name="LunchDetails[${rowCount}].Price" min="0" step="0.01" value="0">
                </td>
                <td>
                    <input type="number" class="form-control total" name="LunchDetails[${rowCount}].TotalAmount" min="0" step="0.01" value="0" readonly>
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                </td>
            `;
            
            // 为新添加的输入框初始化自动完成功能
            const newInput = row.querySelector('.ingredient-autocomplete');
            newInput.addEventListener('input', function() {
                const value = this.value.toLowerCase();
                const rowIndex = this.getAttribute('data-row-index');
                const mealType = this.getAttribute('data-meal-type');
                const suggestionsContainer = document.getElementById('ingredientSuggestions-' + rowIndex + '-' + mealType);
                
                if (value.length < 1) {
                    suggestionsContainer.innerHTML = '';
                    suggestionsContainer.classList.remove('show');
                    return;
                }
                
                // 过滤食材
                const filteredIngredients = ingredients.filter(ingredient => 
                    ingredient.name.toLowerCase().includes(value)
                );
                
                // 显示建议
                displayIngredientSuggestions(filteredIngredients, suggestionsContainer, this);
            });
            
            // 点击其他地方隐藏建议
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                        container.innerHTML = '';
                        container.classList.remove('show');
                    });
                }
            });
            
            // 添加事件监听器
            addCalculationListeners(row);
        }
        
        // 添加晚餐食材行
        function addDinnerDetail() {
            var table = document.getElementById("dinnerDetailsTable").getElementsByTagName('tbody')[0];
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            
            row.innerHTML = `
                <td>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="form-control ingredient-autocomplete" name="DinnerDetails[${rowCount}].IngredientName" data-row-index="${rowCount}" data-meal-type="dinner">
                        <input type="hidden" name="DinnerDetails[${rowCount}].IngredientId" value="0" class="ingredient-id">
                        <input type="hidden" name="DinnerDetails.Index" value="${rowCount}" />
                        <div class="autocomplete-suggestions" id="ingredientSuggestions-${rowCount}-dinner"></div>
                    </div>
                </td>
                <td>
                    <input type="text" class="form-control" name="DinnerDetails[${rowCount}].IngredientUnit">
                </td>
                <td>
                    <input type="number" class="form-control quantity" name="DinnerDetails[${rowCount}].Quantity" min="0" step="0.001" value="0">
                </td>
                <td>
                    <input type="number" class="form-control price" name="DinnerDetails[${rowCount}].Price" min="0" step="0.01" value="0">
                </td>
                <td>
                    <input type="number" class="form-control total" name="DinnerDetails[${rowCount}].TotalAmount" min="0" step="0.01" value="0" readonly>
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">删除</button>
                </td>
            `;
            
            // 为新添加的输入框初始化自动完成功能
            const newInput = row.querySelector('.ingredient-autocomplete');
            newInput.addEventListener('input', function() {
                const value = this.value.toLowerCase();
                const rowIndex = this.getAttribute('data-row-index');
                const mealType = this.getAttribute('data-meal-type');
                const suggestionsContainer = document.getElementById('ingredientSuggestions-' + rowIndex + '-' + mealType);
                
                if (value.length < 1) {
                    suggestionsContainer.innerHTML = '';
                    suggestionsContainer.classList.remove('show');
                    return;
                }
                
                // 过滤食材
                const filteredIngredients = ingredients.filter(ingredient => 
                    ingredient.name.toLowerCase().includes(value)
                );
                
                // 显示建议
                displayIngredientSuggestions(filteredIngredients, suggestionsContainer, this);
            });
            
            // 点击其他地方隐藏建议
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    document.querySelectorAll('.autocomplete-suggestions').forEach(container => {
                        container.innerHTML = '';
                        container.classList.remove('show');
                    });
                }
            });
            
            // 添加事件监听器
            addCalculationListeners(row);
        }
        
        // 删除行
        function removeRow(button) {
            var row = button.parentNode.parentNode;
            row.parentNode.removeChild(row);
            updateTotals();
        }
        
        // 添加计算监听器
        function addCalculationListeners(row) {
            var quantityInput = row.querySelector('.quantity');
            var priceInput = row.querySelector('.price');
            var totalInput = row.querySelector('.total');
            
            if (quantityInput && priceInput && totalInput) {
                function calculateTotal() {
                    var quantity = parseFloat(quantityInput.value) || 0;
                    var price = parseFloat(priceInput.value) || 0;
                    var total = quantity * price;
                    totalInput.value = total.toFixed(2);
                    updateTotals();
                }
                
                quantityInput.addEventListener('input', calculateTotal);
                priceInput.addEventListener('input', calculateTotal);
            }
        }
        
        // 更新总计
        function updateTotals() {
            // 更新早餐总计
            var breakfastTotal = 0;
            document.querySelectorAll('#breakfastDetailsTable .total').forEach(function(element) {
                breakfastTotal += parseFloat(element.value) || 0;
            });
            document.getElementById('breakfastTotal').textContent = breakfastTotal.toFixed(2);
            
            // 更新午餐总计
            var lunchTotal = 0;
            document.querySelectorAll('#lunchDetailsTable .total').forEach(function(element) {
                lunchTotal += parseFloat(element.value) || 0;
            });
            document.getElementById('lunchTotal').textContent = lunchTotal.toFixed(2);
            
            // 更新晚餐总计
            var dinnerTotal = 0;
            document.querySelectorAll('#dinnerDetailsTable .total').forEach(function(element) {
                dinnerTotal += parseFloat(element.value) || 0;
            });
            document.getElementById('dinnerTotal').textContent = dinnerTotal.toFixed(2);
        }
        
        // 页面加载完成后添加事件监听器
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化自动完成数据
            initializeAutocompleteData();
            
            // 初始化自动完成功能
            setTimeout(initializeAutocomplete, 500); // 等待数据加载完成
            
            // 为现有行添加计算监听器
            document.querySelectorAll('#breakfastDetailsTable tbody tr').forEach(function(row) {
                addCalculationListeners(row);
            });
            
            document.querySelectorAll('#lunchDetailsTable tbody tr').forEach(function(row) {
                addCalculationListeners(row);
            });
            
            document.querySelectorAll('#dinnerDetailsTable tbody tr').forEach(function(row) {
                addCalculationListeners(row);
            });
        });
    </script>
    
    <style>
        .autocomplete-wrapper {
            position: relative;
        }
        
        .autocomplete-suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 1000;
            background: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            max-height: 200px;
            overflow-y: auto;
            display: none;
        }
        
        .autocomplete-suggestions.show {
            display: block;
        }
        
        .suggestions-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .suggestions-list li {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        
        .suggestions-list li:hover {
            background-color: #f5f5f5;
        }
        
        .suggestions-list li:last-child {
            border-bottom: none;
        }
    </style>
}